package com.igeek.d0619.test3;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;
import java.util.Arrays;

/**
 * @Author: zhiyu
 * @Date:17:32
 * @DESC:
 */
public class CglibProxy {
    private Calculator target;

    public CglibProxy(Calculator target) {
        this.target = target;
    }
    public Calculator getProxy() {
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(target.getClass());
        enhancer.setCallback(new MethodInterceptor() {
            @Override
            public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
                System.out.println("cglib---开始日志记录，追踪的方法是" + method.getName() + ",objectss=" + Arrays.toString(objects));
                long start = System.currentTimeMillis();
                Object result = method.invoke(target, objects);
                long end = System.currentTimeMillis();
                System.out.println("cglib---结束日志追踪，，追踪的方法是" + method.getName() + ",执行结果是" + result + "此方法耗时=" + (end - start) / 1000.0 + "s");
                return result;
            }
        });
        Object proxy = enhancer.create();
        return (Calculator)proxy;
    }
}
